<script setup>
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'
import { ref } from 'vue'


import useUserInfoStore from '@/stores/userinfo'
//获取个人信息
const userInfoStore = useUserInfoStore();
const userInfo = ref({...userInfoStore.info})

console.log('当前用户角色：', userInfo.value.role) // 确认实际角色值

//数据模型 一个数组三个js对象
const loan = ref([])
//声明一个异步的函数 页面加载完成就得调用方法展示查询结果 调用函数时需要同步等待返回结果
import {loanListService,loanAddService,loanUpdateService,loanDeleteService,loanSelectNeedService} from '@/api/loan.js'
//控制抽屉是否显示
const visibleDrawer = ref(false)
const loanList = async(status='') =>{
    let result
    if(userInfo.value.role===true){
        if(status){
            result = await loanSelectNeedService({loanStatus:status})
        }
        else{
            result = await loanListService()
        }
    }else{
        //仅查询自己的 仅把userId传回去
        result = await loanSelectNeedService({ 
            userId: userInfo.value.userId // 直接传递当前用户ID，不依赖familyModel
        })
    }
    loan.value = result.data
}
loanList();//调用
//401没有携带token过来访问后台时 向后台发送请求时需携带token


//控制添加分类弹窗 控制弹窗显示默认false
const dialogVisible = ref(false)

//添加分类数据模型
const loanModel = ref({
    idCard:'',
    name:'',
    userId:'',
    school: '',
    loanBank: '',
    loanStatus:'',
    loanAmount:'',
    loanTerm:'',
    studentType:'',
    loanStuff:'',
    createTime:''
})
//添加分类表单校验
const rules = {
    school: [
        { required: true, message: '请输入学校', trigger: 'blur' },
    ],
    loanAmount: [
        { required: true, message: '请输入贷款金额', trigger: 'blur' },
    ],
    loanTerm: [
        { required: true, message: '请输入贷款期限', trigger: 'blur' },
    ],
}


//调用接口添加表单
import { ElMessage } from 'element-plus'
const addLoan = async() =>{
    //调用接口
    let result = await loanAddService(loanModel.value)
    ElMessage.success(result.msg?result.msg:'添加成功')

    //刷新一下 获取所有文章分类
    loanList();
    visibleDrawer.value=false;
}

//定义变量控制标题的展示
const title = ref('')

//编辑家庭
const updateLoan = async()=>{
    //调用接口
    let result = await loanUpdateService(loanModel.value)
    ElMessage.success(result.msg?result.msg:'修改成功 ')

    loanList();
    visibleDrawer.value=false;
}

//清空模型的数据 防止编辑之后添加家庭会数据回写 点击添加家庭时数据清空
const clearData = () =>{
    loanModel.value.school='',
    loanModel.value.loanBank='',
    loanModel.value.loanAmount='',
    loanModel.value.loanTerm='',
    loanModel.value.studentType='',
    loanModel.value.loanStuff=''
    loanModel.value.loanId=''
}

import { ElMessageBox } from 'element-plus'
const deleteLoan = (row) =>{
    //提示用户 cv
    ElMessageBox.confirm(
    '确认删除吗?',
    '提示',
    {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    }
    )
    .then(async() => {
        //调用接口
        let result = await loanDeleteService(row.loanId);
    ElMessage({
        type: 'success',
        message: '删除成功',
    })
    //刷新列表
    loanList();
    })
    .catch(() => {
    ElMessage({
        type: 'info',
        message: '删除取消',
    })
    })
    //cv

    }




const currentAuditId = ref('')
const auditDialogVisible = ref(false)

// 显示审核确认弹窗
const showAuditConfirm = (row, isPass) => {
  currentAuditId.value = row.loanId
  ElMessageBox.confirm(
    `确认要${isPass ? '通过' : '驳回'}该家庭的补助申请吗？`,
    '审核确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: isPass ? 'success' : 'warning'
    }
  )
  .then(async () => {
    // 调用更新接口修改审核状态
    const result = await loanUpdateService({
      loanId: currentAuditId.value,
      loanStatus: isPass ? '已通过' : '不通过'
    })
    ElMessage.success(`审核${isPass ? '通过' : '驳回'}成功`)
    loanList() // 刷新列表
  })
  .catch(() => {
    ElMessage.info('已取消审核')
  })
}







import {Plus} from '@element-plus/icons-vue'

//导入token
import { useTokenStore } from '@/stores/token.js'
const tokenStore = useTokenStore();

//上传成功的回调函数 响应的结果.data就是url地 址
const uploadSuccess = (result)=>{
    loanModel.value.loanStuff = result//赋值成功后添加时地址携带给服务器
    console.log(result)
}



//展示编辑弹窗 row用来接收点击编辑时这一行的数据
//一点击编辑按钮，familyModel.value的各项就自动=row的各项 再把familyModel传给updateFamily就可给后台完成修改
const showDialog = (row)=>{
    visibleDrawer.value = true;//放进标签里不用.value
    title.value='编辑贷款'
    //数据拷贝 修改时的回写也就是展示出来在这一行的数据在修改弹窗上
    loanModel.value.school=row.school;
    loanModel.value.loanBank=row.loanBank;
    loanModel.value.loanAmount=row.loanAmount;
    loanModel.value.loanTerm = row.loanTerm;//扩展id属性将来传递给后台完成修改
    loanModel.value.studentType = row.studentType;
    loanModel.value.loanStuff=row.loanStuff
    loanModel.value.loanId = row.loanId;
}


const viewDialogVisible = ref(false)
const currentLoan = ref({})

const showloan = (row) =>{
    currentLoan.value = {...row}
    viewDialogVisible.value=true
}

//下拉框选中的状态
const loanSelectId=ref('')
</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>学生贷款</span>
                <div class="extra">
                    <el-button type="primary" @click="visibleDrawer=true; title='添加学生'; clearData();loanModel.userId=userInfo.userId" v-if="userInfo.role===false">添加学生</el-button>
                </div>
            </div>
        </template>




        <!-- 搜索表单 -->
        <el-form inline v-if="userInfo.role===true">
            <el-form-item label="审核状态">
                <el-select placeholder="请选择" v-model="loanSelectId" style="width: 240px;">
                    <el-option label="待审核" value="待审核"></el-option>
                    <el-option label="已通过" value="已通过"></el-option>
                    <el-option label="不通过" value="不通过"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="loanList(loanSelectId)">搜索</el-button>
                <el-button @click="()=>{loanSelectId='';loanList()}">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 家庭列表表格 prop告诉表格去每一行数据找到对应属性并展示-->
        <el-table :data="loan" style="width: 100%">
            <el-table-column label="序号" width="100" type="index"></el-table-column>
            <el-table-column label="身份证号" prop="idCard" v-if="userInfo.role===1 || userInfo.role===true"></el-table-column>
            <el-table-column label="姓名" prop="name" v-if="userInfo.role===1 || userInfo.role===true"></el-table-column>
            <el-table-column label="学校" prop="school" v-if="userInfo.role===0 || userInfo.role === false"></el-table-column>
            <el-table-column label="贷款银行" prop="loanBank" v-if="userInfo.role===0 || userInfo.role === false"></el-table-column>
            <el-table-column label="贷款金额" prop="loanAmount" v-if="userInfo.role===0 || userInfo.role === false"></el-table-column>
            <el-table-column label="贷款期限" prop="loanTerm" v-if="userInfo.role===0 || userInfo.role === false"></el-table-column>
            <el-table-column label="资料" v-if="userInfo.role===1 || userInfo.role === true">
                <template #default="{row}">
                    <el-button type="primary" plain size="small" @click="showloan(row)">
                            查看详情
                    </el-button>
                </template>
                </el-table-column>
            <el-table-column label="贷款资料" prop="loanStuff" v-if="userInfo.role === false">
            <template #default="{ row }">
                <!-- 有资料地址时显示超链接 
                 地址
                 新窗口展示
                 超链接样式-->
                <template v-if="row.loanStuff">
                <a 
                    :href="row.loanStuff" 
                    target="_blank" 
                    style="color: #409eff; text-decoration: underline"
                >
                    查看
                </a>
                </template>
                <!-- 无资料时显示提示文字 -->
                <template v-else>
                <span style="color: #909399">无资料</span>
                </template>
            </template>
            </el-table-column>
            <el-table-column label="学生类型" prop="studentType" v-if="userInfo.role===false"></el-table-column>
            <el-table-column label="申请时间" prop="createTime">
                <template #default="{ row }">
                    {{ row.createTime ? new Date(row.createTime).toLocaleString() : '-' }}
                </template>
            </el-table-column>
            <el-table-column label="审核状态" prop="loanStatus" >
                <template #default="{ row }">
                    <el-tag 
                        :type="row.loanStatus === '已通过' ? 'success' : 
                               row.loanStatus === '不通过' ? 'danger' : 'warning'"
                    >
                        {{ row.loanStatus }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="300" v-if="userInfo.role===false">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="deleteLoan(row)"></el-button>
                    
                    
                </template>
            </el-table-column>


            <!-- 管理员操作列：仅显示审核按钮 -->
<el-table-column label="操作" width="200" v-if="userInfo.role===true">
  <template #default="{ row }">
    <!-- 仅待审核状态显示审核按钮 -->
    <template v-if="row.loanStatus === '待审核'">
      <el-button type="success" plain size="small" @click="showAuditConfirm(row, true)">
        审核通过
      </el-button>
      <el-button type="danger" plain size="small" @click="showAuditConfirm(row, false)">
        审核不通过
      </el-button>
    </template>
    <!-- 已审核状态显示提示（无操作按钮） -->
    <template v-else>
      <span style="color: #909399">已审核</span>
    </template>
  </template>
</el-table-column>




            <template #empty>
                <el-empty description="没有数据" />
            </template>
            
        </el-table>


        <!-- 抽屉 -->
        <el-drawer v-model="visibleDrawer" title="添加学生" direction="rtl" size="50%">
            <!-- 添加文章表单 -->
            <el-form :model="loanModel" label-width="100px" v-if="userInfo.role===false">
                <el-form-item label="学校" >
                    <el-input v-model="loanModel.school" placeholder="请输入学校"></el-input>
                </el-form-item>
                <el-form-item label="贷款银行" prop="loanBank">
                    <el-select v-model="loanModel.loanBank" placeholder="请选择贷款银行">
                        <el-option label="国家开发银行" value="国家开发银行"></el-option>
                        <el-option label="中国邮政储蓄银行" value="中国邮政储蓄银行"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="贷款金额" >
                    <el-input v-model="loanModel.loanAmount" placeholder="请输入贷款金额"></el-input>
                </el-form-item>
                <el-form-item label="贷款期限" >
                    <el-input v-model="loanModel.loanTerm" placeholder="请输入贷款期限"></el-input>
                </el-form-item>
                <el-form-item label="学生类型" prop="studentType">
                    <el-select v-model="loanModel.studentType" placeholder="请选择学生类型">
                        <el-option label="本专科生" value="本专科生"></el-option>
                        <el-option label="研究生" value="研究生"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="学生资料">

                    <!--
                    auto-upload：设置是否自动上传
                    action:服务器接口路径
                    name:上传的文件字段名
                    headers：上传的请求头
                    on-success:上传成功的回调函数
                    /upload标签自动发送ajax请求
                    -->
                    <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
                    action="/api/loan/upload"
                    name="file"
                    :headers="{'Authorization':tokenStore.token}"
                    :on-success="uploadSuccess">
                        <img v-if="loanModel.loanStuff" :src="loanModel.loanStuff" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="visibleDrawer = false">取消</el-button>
                    <!-- 与上面关联添加学生标签关联 -->
                    <el-button type="primary" @click="title === '添加学生' ? addLoan() : updateLoan()">确认</el-button>
                </span>
            </template>
        </el-drawer>



        <el-dialog
        title="家庭详情"
        v-model="viewDialogVisible"
        width="50%"
        :close-on-click-modal="false"
        >
        <el-card class="page-container">
            <template #header>
            <div class="header">
                <span>贷款基本信息</span>
            </div>
            </template>
            <el-row>
            <el-col :span="12">
                <el-form :model="currentLoan" label-width="120px" size="large">
                <el-form-item label="贷款银行">
                    <el-input v-model="currentLoan.loanBank" disabled></el-input>
                </el-form-item>
                <el-form-item label="贷款金额">
                    <el-input v-model="currentLoan.loanAmount" disabled></el-input>
                </el-form-item>
                <el-form-item label="贷款期限">
                    <el-input v-model="currentLoan.loanTerm" disabled></el-input>
                </el-form-item>
                <el-form-item label="学生类型">
                    <el-input v-model="currentLoan.studentType" disabled></el-input>
                </el-form-item>
                <el-form-item label="家庭资料">
                    <template v-if="currentLoan.loanStuff">
                    <a 
                        :href="currentLoan.loanStuff" 
                        target="_blank" 
                        style="color: #409eff; text-decoration: underline"
                    >
                        点击查看资料
                    </a>
                    </template>
                    <template v-else>
                    <el-input value="无资料" disabled></el-input>
                    </template>
                </el-form-item>
                <el-form-item label="申请时间">
                    <el-input 
                    :value="currentLoan.createTime ? new Date(currentLoan.createTime).toLocaleString() : '-'" 
                    disabled
                    ></el-input>
                </el-form-item>
                <el-form-item label="审核状态">
                    <el-input v-model="currentLoan.loanStatus" disabled></el-input>
                </el-form-item>
                </el-form>
            </el-col>
            </el-row>
        </el-card>
        </el-dialog>
    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}




.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>